package com.example.myproject.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface TorrentTagMapper {
    @Insert("INSERT INTO torrent_tag (torrent_id, tag_id) VALUES (#{torrentId}, #{tagId})")
    void insert(@Param("torrentId") Long torrentId, @Param("tagId") Long tagId);

    @Select("SELECT tag_id FROM torrent_tag WHERE torrent_id = #{torrentId}")
    List<Long> selectTagIdsByTorrentId(Long torrentId);

    @Select("SELECT t.tag_name FROM tag t JOIN torrent_tag tt ON t.tag_id = tt.tag_id WHERE tt.torrent_id = #{torrentId}")
    List<String> selectTagNamesByTorrentId(Long torrentId);

    @Select({
            "<script>",
            "SELECT tt.torrent_id",
            "FROM   torrent_tag tt",
            "JOIN   tag t USING (tag_id)",
            "WHERE  t.tag_name IN",
            "  <foreach collection='tagNames' item='name' open='(' separator=',' close=')'>",
            "    #{name}",
            "  </foreach>",
            "GROUP BY tt.torrent_id",
            "HAVING COUNT(DISTINCT t.tag_name) = #{tagCount}",
            "</script>"
    })
    List<Long> findTorrentIdsByTagNames(@Param("tagNames") List<String> tagNames,
                                        @Param("tagCount") Integer tagCount);

    @Select({
            "<script>",
            "SELECT torrent_id ",
            "FROM   torrent_tag ",
            "WHERE  tag_id IN ",
            "<foreach collection='tagIds' item='id' open='(' separator=',' close=')'>",
            "  #{id}",
            "</foreach>",
            "GROUP BY torrent_id ",
            "HAVING COUNT(DISTINCT tag_id) = #{cnt}",
            "</script>"
    })
    List<Long> findTorrentIdsByTags(@Param("tagIds") List<Long> tagIds,
                                    @Param("cnt") Integer cnt);
}

